package com.example.myapplication.LocationTest;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.example.myapplication.BroadcastTest.BroadcastTestActivity;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;


public class LocationActivity extends AppCompatActivity {
  private static final String BD_KEY = "oFBqR52fjSGchI0V5ZNgHyAVPCzooBhg";
  private Handler handler = new Handler();
  private static final int REQUEST_LOCATION_PERMISSION = 100;

  private MapView mapView;
  private BaiduMap baiduMap;
  private LocationClient locationClient;


  private BDLocationListener locationListener;
  TextView textView;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    SDKInitializer.setAgreePrivacy(getApplicationContext(),true);
    SDKInitializer.initialize(this.getApplicationContext());
    super.onCreate(savedInstanceState);

    setContentView(R.layout.location_layout);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setTitle("百度地图定位测试");
    setSupportActionBar(toolbar);

    Init();
  }

  private void Init() {
    textView = findViewById(R.id.location_info);
    textView.setVisibility(View.INVISIBLE);
    mapView = findViewById(R.id.map_view);
    mapView.setVisibility(View.GONE);

    baiduMap = mapView.getMap();
    Button showButton = findViewById(R.id.message_button);
    Button mapButton = findViewById(R.id.location_button);
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
      //请求定位权限
      ActivityCompat.requestPermissions(this,
          new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION_PERMISSION);
    } else {
      //已有定位权限，进行定位初始化
      try {
        initLocation();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    mapButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        JumpToMapView();
      }
    });
    showButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        ShowInfo();
      }
    });
  }

  private void ShowInfo() {
    textView.setVisibility(View.VISIBLE);

  }
  private void initLocation() throws Exception {
    locationClient.setAgreePrivacy(true);
    locationClient = new LocationClient(getApplicationContext());

    locationListener = new MyLocationListener(baiduMap, mapView, textView);
    locationClient.registerLocationListener(locationListener);

    //配置定位选项
    LocationClientOption option = new LocationClientOption();
    option.setPriority(LocationClientOption.NETWORK_FIRST);//设置网络优先(不设置，默认是gps优先)
    option.setScanSpan(2000);//定位间隔，单位毫秒
    option.setCoorType("bd0911");//设置坐标类型为百度经纬度
    //setOpenGps已经过时
    option.setOpenGps(true);//打开GPS

    locationClient.setLocOption(option);
    //开始定位
    locationClient.start();
  }

  private void JumpToMapView() {
    Intent intent = new Intent(this, LocationMapViewActivity.class);
    startActivity(intent);

  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 1, 0, "返回上一个Activity");
    menu.add(0, 2, 1, "跳转到下一个Activity");
    return true;
  }

  @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case 1:
        BackToLastActivity();
        break;
      case 2:
        GoToNextActivity();
        break;
    }
    return true;
  }

  private void GoToNextActivity() {
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
  }
  private void BackToLastActivity() {
    Intent intent = new Intent(this, BroadcastTestActivity.class);
    startActivity(intent);

  }
  @Override protected void onResume() {
    super.onResume();
    mapView.onPause();

  }

  @Override protected void onDestroy() {
    super.onDestroy();
    //停止定位并释放资源
    locationClient.stop();
    locationClient.unRegisterLocationListener(locationListener);
    mapView.onDestroy();
    baiduMap.setMyLocationEnabled(false);

  }

  @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
      @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_LOCATION_PERMISSION) {
      //定位权限已经授予，进行定位初始化
      try {
        initLocation();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    } else {
      //定位权限被拒绝
      Toast.makeText(this, "定位权限被拒绝，无法进行定位", Toast.LENGTH_SHORT).show();
    }
  }

}
